package com.qs.cwams.util;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author suncheng
 */
public class CalcDuration {

    private final AtteStandard standard;

    public CalcDuration() {
        standard = new AtteStandard();
    }

    public AtteStandard getStandard() {
        return standard;
    }

    /**
     * 计算请假一天时长
     * @param startTime
     * @param endTime
     * @return
     */
    public long durationOfDay(LocalDate date, LocalDateTime startTime, LocalDateTime endTime) {
        long minutes = 0;
        if (Duration.between(startTime, endTime).toMinutes() <= 0) {
            return minutes;
        }
        AtteDailyTime daily = new AtteDailyTime(date);
        TimeSlot leave = new TimeSlot(startTime, endTime);
        if (daily.getWorkTime().size() > 0) {
            for (TimeSlot work : daily.getWorkTime()) {
                TimeSlot time = work.intersect(leave);
                if (time != null) {
                    minutes += time.duration();
                }
            }
        }
        return minutes;
    }

    /**
     * 计算请假总时长
     * @param startTime
     * @param endTime
     * @return
     */
    public long total(Date startTime, Date endTime) {
        LocalDateTime start = LocalDateTime.ofInstant(startTime.toInstant(), ZoneId.systemDefault());
        LocalDateTime end = LocalDateTime.ofInstant(endTime.toInstant(), ZoneId.systemDefault());

        long minutes = 0;
        long days = Duration.between(start, end).toDays();
        if (days == 0) {
            // 请假一天
            minutes = durationOfDay(start.toLocalDate(), start, end);
        } else {
            // 请假多天
            minutes += durationOfDay(start.toLocalDate(), start, LocalDateTime.of(start.toLocalDate(), standard.getPmEndTime()));
            for (int i = 1; i <= (days - 1); i++) {
                LocalDate date = start.toLocalDate().plusDays(i);
                minutes += durationOfDay(date, LocalDateTime.of(date, standard.getAmStartTime()),  LocalDateTime.of(date, standard.getPmEndTime()));
            }
            minutes += durationOfDay(end.toLocalDate(), LocalDateTime.of(end.toLocalDate(), standard.getAmStartTime()), end);
        }
        return minutes;
    }
}
